package com.cskaoyan.transfer;

import com.cskaoyan.utils.JDBCUtils;
import com.cskaoyan.utils.JDBCUtils2;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * 创建日期: 2022/07/26 17:26
 *
 * @author ciggar
 *
 * 事务
 */
public class TransferDemo {


    public static void main(String[] args) throws SQLException {


        Boolean ret = transfer("风华哥", "长风", 1000);

        if (ret){
            System.out.println("转账成功！");
        }else {
            System.out.println("转账失败！");
        }


    }



    // 转账方法
    /**
     * 创建日期：2022/07/26 17:28
     * @param fromName  转账发起人
     * @param toName    转账受益人
     * @param money     转账金额
     * @return java.lang.Boolean true: 成功   false：失败
     * @author ciggar
     */
    public static Boolean transfer(String fromName,String toName,Integer money) throws SQLException {

        Boolean flag = false;

        // 获取连接
        Connection connection = JDBCUtils2.getConnection();

        // 开启事务
        connection.setAutoCommit(false);

        try {

            // 扣钱
            PreparedStatement preparedStatement = connection.prepareStatement("update account set money = money - ? where name = ? and money >= ?");
            preparedStatement.setInt(1, money);
            preparedStatement.setString(2, fromName);
            preparedStatement.setInt(3, money);
            int affectedRows = preparedStatement.executeUpdate();

            if (affectedRows == 0) {
                throw new RuntimeException("扣钱失败！");
            }

            // int i = 1 / 0;

            // 加钱
            PreparedStatement preparedStatement2 = connection.prepareStatement("update account set money = money + ? where name = ?");
            preparedStatement2.setInt(1, money);
            preparedStatement2.setString(2, toName);
            int affectedRows2 = preparedStatement2.executeUpdate();

            if (affectedRows2 == 0) {
                throw  new RuntimeException("加钱失败！");
            }
            // 提交事务
            connection.commit();
            flag = true;

        }catch (Exception ex) {
            ex.printStackTrace();
            // 回滚事务
            connection.rollback();
            flag = false;
        }
        return flag;


    }
}
